<template>
  <van-popup v-model:show="showTop" position="top">
    <div class="flex flex-col h-[600px] overflow-y-auto">
      <div class="flex flex-col px-5 py-5 flex-auto overflow-y-auto">
        <slot></slot>
        <div class="mt-4">
          <h2 class="text-sm font-medium text-gray-900 mb-5">时间范围</h2>
          <div
            class="date-picker-trigger inline-flex items-center justify-between p-3 rounded-lg bg-gray-50 hover:bg-gray-100 cursor-pointer"
            @click="showDatePicker = true"
          >
            <div class="text-sm">
              {{ cp_dateRangeDes }}
            </div>
            <van-icon name="arrow" class="text-gray-400 ml-2" />
          </div>
        </div>
        <div class="mt-4 flex-1" v-for="(item, index) in dataSource" :key="index">
          <h2 class="text-sm font-medium text-gray-900 mb-5">
            {{ item.title }}
          </h2>

          <div v-if="item.key === 'stages'">
            <AllStagesView
              ref="allStagesViewRef"
              :items="item.items"
              @change="onChangeStages"
            />
          </div>

          <div
            v-if="item.key !== 'stages'"
            :class="
              item.useFlex
                ? 'flex flex-row flex-wrap'
                : 'grid grid-cols-4 gap-2 text-nowrap'
            "
          >
            <div
              :class="`tag ${subItem.selected ? 'active-tag' : ''} `"
              :style="{ marginBottom: item.useFlex ? '10px' : '0' }"
              @click="onClickTag(subItem, item)"
              v-for="subItem in item.items"
              :key="subItem"
            >
              {{ subItem.label }}
            </div>
          </div>
        </div>
      </div>

      <van-divider class="my-0" />

      <div class="flex flex-row justify-between p-3">
        <van-button type="default" block @click="resetAction">重置</van-button>
        <div class="w-[50px]"></div>
        <van-button type="primary" color="#436BFF" block @click="confirmAction"
          >完成</van-button
        >
      </div>
      <DateSelectView
        :is-popup="true"
        v-model:show="showDatePicker"
        :default-date="dateRange"
        @confirm="onDateSelect"
      />
    </div>
  </van-popup>
</template>

<script setup>
import { ref, defineExpose, computed, defineEmits, onMounted, defineProps } from "vue";
import { useMyXmateStore, useCommonStore } from "@/store";
import DateSelectView from "@/components/dateSelectView.vue";
import AllStagesView from "./allStagesView.vue";

const store = useMyXmateStore();
const commonStore = useCommonStore();
const emits = defineEmits(["onConfirm"]);
//
const cp_communicationFlows = computed(() => store.communicationFlows);

const props = defineProps({
  enableCRM: {
    type: Boolean,
    default: true,
  },
  defaultDateRange: {
    // 新增默认时间范围属性
    type: Array,
    default: () => null,
  },
});

onMounted(async () => {
  await commonStore.getFuncpPointsAction();
  setDataSource();
});

const showDatePicker = ref(false);
const dateRange = ref(props.defaultDateRange || null);
const onDateSelect = (range) => {
  dateRange.value = range;
  showDatePicker.value = false;
};

const cp_dateRangeDes = computed(() => {
  if (dateRange.value) {
    return `${dateRange.value[0]} 至 ${dateRange.value[1]}`;
  } else if (props.defaultDateRange) {
    return `${props.defaultDateRange.value?.[0]} 至 ${props.defaultDateRange.value?.[1]}`;
  }
  return "选择日期1";
});

const cp_salesCRMUpdateFilter = computed(() => commonStore.cp_salesCRMUpdateFilter);

const dataSource = ref([]);
function setDataSource() {
  console.log("setDataSource: ", props.defaultDateRange);
  let arr = [];

  arr.push({
    title: "处理状态",
    key: "reportStatus",
    useFlex: true,
    allowCancel: true,
    allowMultiple: false,
    items: [
      {
        label: "处理失败",
        value: "RECORD_FAIL",
      },
      {
        label: "处理中",
        value: "IN_PROCESS",
      },
      {
        label: "字幕不足",
        value: "LITTLE_CONTENT",
      },
      {
        label: "未标注",
        value: "NEED_ANNOTATION",
      },
      {
        label: "未点生成",
        value: "NEED_GENERATE",
      },
      {
        label: "生成失败",
        value: "FAIL",
      },
      {
        label: "生成成功",
        value: "SUCCESS",
      },
    ],
  });

  // TODO ： 添加要素控制
  if (props.enableCRM && cp_salesCRMUpdateFilter) {
    arr.push({
      title: "CRM同步状态",
      allowCancel: true,
      key: "syncStatus",
      useFlex: true,
      allowMultiple: false,
      items: [
        {
          label: "未同步",
          value: "NO_SYNC",
        },
        {
          label: "已同步",
          value: "SUCCESS",
        },
        {
          label: "同步失败",
          value: "FAIL",
        },
        {
          label: "客户不存在",
          value: "NO_CUSTOMER",
        },
      ],
    });
  }

  arr.push({
    allowMultiple: true,
    allowCancel: true,
    useFlex: true,
    title: "沟通环节",
    key: "stages",
    items: cp_communicationFlows.value,
  });

  arr.push({
    title: "能力评估",
    key: "abilityStatus",
    useFlex: true,
    allowCancel: true,
    allowMultiple: false,
    items: [
      {
        label: "达标",
        value: 1,
      },
      {
        label: "未达标",
        value: 0,
      },
    ],
  });

  arr.push({
    title: "任务达成",
    key: "taskStatus",
    useFlex: true,
    allowCancel: true,
    allowMultiple: false,
    items: [
      {
        label: "达标",
        value: 1,
      },
      {
        label: "未达标",
        value: 0,
      },
    ],
  });

  dataSource.value = arr;
}

const showTop = ref(false);

function show() {
  // 初始化时设置日期范围
  showTop.value = true;
}

function hide() {
  showTop.value = false;
}

function onClickTag(tag, sessionItem) {
  if (sessionItem.allowMultiple) {
    // 处理多选情况
    tag.selected = !tag.selected;
    return;
  }

  sessionItem.items.forEach((tempItem) => {
    if (tempItem.value == tag.value) {
      tempItem.selected = sessionItem.allowCancel ? !tag.selected : true;
    } else {
      tempItem.selected = false;
    }
  });
}

const selectedStageIds = ref([]);
function onChangeStages(stages) {
  selectedStageIds.value = stages.map((v) => v.id);
}

function confirmAction() {
  let parameter = {};
  let haveCondition = false;
  dataSource.value.forEach((v) => {
    const { key, allowMultiple, items } = v;
    let selectedArr = items.filter((v) => v.selected).map((v) => v.value);
    if (selectedArr.length > 0) {
      haveCondition = true;
      parameter[key] = allowMultiple ? selectedArr : selectedArr[0];
    }
  });

  // 添加日期范围到参数中
  if (dateRange.value) {
    haveCondition = true;
    parameter.dateRange = dateRange.value;
  }
  if (selectedStageIds.value.length > 0) {
    haveCondition = true;
    parameter.stageIds = selectedStageIds.value;
  }

  if (!haveCondition) parameter = {};
  console.log("confirmAction: ", parameter);

  emits("onConfirm", parameter);
  hide();
}

const allStagesViewRef = ref(null);
function resetAction() {
  dataSource.value.forEach((item) => {
    item.items.forEach((v) => {
      v.selected = false;
      if (v.value === "quarter") {
        v.selected = true;
      }
    });
  });
  selectedStageIds.value = [];

  allStagesViewRef.value[0].resetAction();
  // dateRange.value = null; // 重置日期范围
}

defineExpose({
  show,
  hide,
});
</script>

<style lang="less" scoped>
.tag {
  padding: 5px 12px;
  background-color: #f4f5f5;
  font-weight: 400;
  font-size: 12px;
  color: #262626;
  line-height: 18px;
  margin: 0 16px 4px 0;
  border-radius: 4px;
  text-align: center;
}

.active-tag {
  color: #436bff;
  background-color: #f0f3ff;
}
</style>
